<template>
  <div class="manager-list-tab-panel">
    <el-form ref="form" :model="form" label-width="0px">
      <div>
        <tx-button-add :name="$dictValue('新增{name}')" @click="handleNew()" />
        <div style="float: right">
          <tx-button-add
            :icon="allowSort ? '' : 'el-icon-tickets'"
            :name="allowSort ? '保存排序' : '修改排序'"
            @click="updateSort"
          /><tx-button-add
            v-if="allowSort"
            icon=""
            name="取消排序"
            class="dialog-cancel-btn"
            style="background: #1d3f6a"
            @click="cancelSort"
          />
        </div>
      </div>
      <tx-list-table
        :table="table"
        ref="listTable"
        row-key="name"
        v-loading="table.loading"
      >
        <tx-table-column-text label="排序" width="60">
          <template slot-scope="scope">{{
            scope.scope.scope.$index + 1
          }}</template>
        </tx-table-column-text>
        <tx-table-column-text :label="$dictValue('姓名')">
          <template slot-scope="scope">
            <tx-table-input
              :entity="scope.row"
              name="name"
              :action="scope.row.$action"
              :rules="formRules.name"
              :prop="buildRowProp(scope, 'name')"
              :placeholder="$dictValue('请输入姓名')"
            />
          </template>
        </tx-table-column-text>
        <tx-table-column-text label="单位">
          <template slot-scope="scope">
            <tx-table-input
              :entity="scope.row"
              name="workUnit"
              :action="scope.row.$action"
              :rules="formRules.workUnit"
              :prop="buildRowProp(scope, 'workUnit')"
              placeholder="请输入单位"
            />
          </template>
        </tx-table-column-text>
        <tx-table-column-text label="职务">
          <template slot-scope="scope">
            <tx-table-input
              :entity="scope.row"
              name="job"
              :action="scope.row.$action"
              :rules="formRules.job"
              :prop="buildRowProp(scope, 'job')"
              placeholder="请输入职务"
            />
          </template>
        </tx-table-column-text>
        <tx-table-column-text label="手机号" width="170">
          <template slot-scope="scope">
            <tx-table-input
              :entity="scope.row"
              name="phone"
              :action="scope.row.$action"
              :rules="formRules.phone"
              :prop="buildRowProp(scope, 'phone')"
              placeholder="请输入手机号"
            />
          </template>
        </tx-table-column-text>
        <tx-table-column-action width="225" align="left" :key="$columnKey()">
          <template slot-scope="scope">
            <el-form
              :ref="`form${scope.scope.scope.$index}`"
              :model="form.record"
              :rules="formRules"
              style="display: none"
            >
              <tx-form-input :entity="form.record" name="name" />
              <tx-form-input :entity="form.record" name="workUnit" />
              <tx-form-input :entity="form.record" name="job" />
              <tx-form-input :entity="form.record" name="phone" />
            </el-form>
            <!-- <tx-link text="编辑" name="dept" :query="{itemId: scope.row.itemId}"  />
                        <tx-link text="删除" name="dept" :query="{itemId: scope.row.itemId}"  />  -->
            <el-button
              type="primary"
              size="mini"
              v-if="scope.row.$action != 'modify'"
              class="table-edit-btn"
              @click="handleEdit(scope)"
              >编辑
            </el-button>
            <el-button
              type="primary"
              size="mini"
              v-if="scope.row.$action == 'modify'"
              @click="handleSave(scope)"
              class="table-save-btn"
              >保存
            </el-button>
            <el-button
              size="mini"
              type="warning"
              v-if="scope.row.$action == 'modify'"
              @click="handleCancel(scope)"
              class="table-cancel-btn"
              >取消
            </el-button>
            <tx-button-text-delete
              class="table-del-btn"
              v-if="scope.row.$action == 'modify'"
              controller="UserController"
              idKey="id"
              :idValue="scope.row.id"
              :body="scope.row"
              :success="$handleQuery"
              target="记录"
            />
          </template>
        </tx-table-column-action>
      </tx-list-table>
      <!-- {{
        $nextTick(() => {
          $initDragTable($refs["listTable"], table.page, "records");
        })
      }} -->
    </el-form>
  </div>
</template>
<script>
export default {
  props: {
    active: {
      type: [String],
      default: "",
    },
    name: {
      type: [String],
      default: "",
    },
    dict: {
      type: Object,
      default() {
        return {
          name: "",
          isLeader: "1",
        };
      },
    },
  },
  data() {
    return {
      allowSort: false,
      table: {
        loading: false,
        query: {},
        sort: {
          descs: ["updateTime"],
        },
        page: this.$yzvue.initPage(),
      },

      // dict: dicts[this.name],
      form: {
        new: {
          name: "",
          workUnit: "",
          job: "",
          phone: "",
          // menuID:"",
          // areaCode:"",
          // createdBy:"",
        },
        record: {
          name: "",
          workUnit: "",
          job: "",
          phone: "",
        },
        records: [],
      },
      formRules: {
        name: this.$rule.name("姓名", null, 32),
        workUnit: this.$rule.name("单位", null, 32),
        job: this.$rule.name("职务", null, 32),
        phone: this.$rule.mobile("手机号", true),
      },
    };
  },
  components: {},
  watch: {
    active: {
      handler(n, o) {
        if (n && n == this.name) {
          this.loadTable();
        }
      },
    },
  },
  mounted() {
    if (this.active == this.name) {
      this.loadTable();
    }
  },

  methods: {
    handlePageChange(size, current) {
      this.loadTable(null, size, current);
    },

    handleNew() {
      let newRow = Object.assign({ $action: "modify" }, this.form.new);
      console.log(newRow);
      this.table.page.records.push(newRow);
      console.log(this.table);
    },

    handleQuery() {
      this.loadTable();
    },

    loadTable() {
      let param = this.$handleQueryParam();
      (param.body.isLeader = this.dict.isLeader), (this.table.loading = true);
      this.$api.UserController.list(param, (res) => {
        this.table.loading = false;
        console.log(res);
        for (let ri = 0; ri < res.data.length; ri++) {
          const re = res.data[ri];
          re.$action = "view";
        }
        this.$yzvue.assembleBody(this.table.page, { records: res.data });
        this.form.records = res.data;
        this.$nextTick(() => {
          this.$initDragTable(
            this.$refs["listTable"],
            this.table.page,
            "records"
          );
        });
      });
    },

    buildRowProp($scope, field) {
      let {
        scope: { scope },
      } = $scope;
      return `records.${scope.$index}.${field}`;
    },

    getQueryParam() {
      let param = this.$yzvue.assemblePage(this.table);
      let query = this.table.query;
      this.$yzvue.appendFilter(param.body.filters, "name", "like", query.name);
      return param;
    },

    // 编辑
    handleEdit($scope) {
      $scope.row.$action = "modify";
      let { name, workUnit, job, phone } = $scope.row;
      $scope.row.$origin = { name, workUnit, job, phone };
    },

    // 保存
    handleSave($scope) {
      Object.assign(this.form.record, $scope.row);
      console.log(this.form.record);
      console.log($scope.row);
      this.$handleFormValidate(`form${$scope.scope.scope.$index}`, () => {
        let { id, name, workUnit, job, phone } = $scope.row;
        let isModify = id;

        let pack = {};
        if (isModify) {
          pack.body = {
            id,
            name,
            workUnit,
            job,
            phone,
            isLeader: this.dict.isLeader,
            createdBy: this.$userInfo.phone,
            menuID: this.getParameter("menuId"),
            areaCode: this.$userInfo.areaCode,
          };
        } else {
          pack.body = {
            id,
            name,
            workUnit,
            job,
            phone,
            isLeader: this.dict.isLeader,
            menuID: this.getParameter("menuId"),
            areaCode: this.$userInfo.areaCode,
            createdBy: this.$userInfo.phone,
          };
        }

        this.table.loading = true;

        let newMethod = this.$api.UserController.new;
        let updateMethod = this.$api.UserController.update;
        this.$invokeSave(pack, "id", newMethod, updateMethod, (res) => {
          this.table.loading = false;
          if (res && res.data) {
            $scope.row.$action = "view";
            if (!isModify) {
              $scope.row.id = res.data;
            }
            this.loadTable();
          }
        });
      });
    },
    // 取消
    handleCancel($scope) {
      Object.assign($scope.row, $scope.row.$origin);
      $scope.row.$action = "view";
      this.$refs["form"].clearValidate();
    },
    //删除
    handleDelete($scope) {
      let {
        scope: { scope },
      } = $scope;
      this.table.page.records.splice(scope.$index, 1);
      // 请求后台接口删除数据库数据
    },
    updateSort() {
      if (this.allowSort == false) {
        this.$initDragTable(
          this.$refs["listTable"],
          this.table.page,
          "records"
        );
        this.beforeSortData = JSON.parse(
          JSON.stringify(this.table.page.records)
        );
      } else {
        let params = this.table.page.records
          ?.filter((i) => i.id)
          ?.map((i, k) => {
            return {
              id: i.id,
              udOrder: k + 1,
            };
          });
        this.$api.UserController.sort({ body: params }, (res) => {
          if (res.code == 0) {
            this.loadTable();
            this.$stopDragTable();
          }
        });
      }
      this.allowSort = !this.allowSort;
    },
    cancelSort() {
      this.allowSort = !this.allowSort;
      // this.this.table.page.records = JSON.parse(JSON.stringify(this.beforeSortData))
      // this.$initDragTable(this.$refs["listTable1"],
      //       this.table.page,
      //       "records1")
      this.$stopDragTable();
      this.loadTable();
    },
  },
};
</script>

<style lang="scss">
$car-table-border-color: #e4e4e4;
$car-table-title-color: #f5f5f5;

.manager-list-tab-panel {
  .tx-list-query {
    margin: 0px;

    // border: 2px solid $c-bd-menu;
  }
  .tx-block {
    width: auto;
    margin: 15px 0px;
    background-color: $c-bg-query;
    border: 1px solid $c-bd-content;
  }

  .el-table td.el-table__cell {
    padding: 8px 0px 0px 0px;
    .cell > span {
      display: block;
      padding-bottom: 13px;
      line-height: 30px;
    }
    .tx-table-column-action {
      display: block;
      padding-bottom: 10px;
    }

    .el-input__inner {
      height: 30px;
      line-height: 30px;
      padding: 0px 5px;
    }
    .el-form-item {
      margin-bottom: 13px;
    }
    .el-form-item__content {
      line-height: 30px;
    }
    .el-form-item__error {
      padding-top: 0px;
    }
  }
}
</style>
